package com.ly.datacenter.jdbc.parser;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;

import com.ly.datacenter.crud.json.CRUDField;
import com.ly.datacenter.database.definition.TableDefinition;

/**
 * function：
 * @author watson  email: watson.wu@hotmail.com
 * @date 2009-9-6
 */
public class JSONParser {
	
	private static final String SUFFIX = ".json";
	private static String path = "/media/dev/workspace/java/j2ee/lianyi/magic-form/conf";
	
	public static JSON getTableDefinition2JSON(String table) {
		try {
			String contentOfTableDefinition = FileUtils.readFileToString(new File(path+"/"+table+SUFFIX), "utf-8");
			JSONArray array = JSONArray.fromObject(contentOfTableDefinition);
			return array;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public static TableDefinition getTableDefinition(String table) {
		try {
			String contentOfTableDefinition = FileUtils.readFileToString(new File(path+"/"+table+SUFFIX), "utf-8");
			JSONArray array = JSONArray.fromObject(contentOfTableDefinition);
			if(array != null){
				List<CRUDField> list = new ArrayList<CRUDField>();
				CRUDField crud;
				for(int i=0;i<array.size();i++) {
					crud = new CRUDField();
					Object object = array.get(i);
					if(object instanceof JSONObject) {
						JSONObject json=(JSONObject)object;
						crud.setName(json.get("name").toString());
						crud.setType(json.get("type").toString());
//						crud.setValue(value);
						crud.setAttrs((Map)json.get("attrs"));
					}
					list.add(crud);
				}
				new TableDefinition(list, true);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		getTableDefinition("users");
	}

}

